package com.graduationproject.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.graduationproject.Util.ValidationUtil;
import com.graduationproject.entity.RelUserRole;
import com.graduationproject.entity.Role;
import com.graduationproject.entity.User;
import com.graduationproject.mapper.UserMapper;
import com.graduationproject.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;


/**
 * @author shkstart
 * @create 2023-12-19-14:00
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RelUserRoleServiceImpl relUserRoleService;

    @Autowired
    private RoleServiceImpl roleService;

    /**
     * 用户登录
     *
     * @param username
     * @param password
     * @return
     */
    @Override
    public User login(String username, String password) {
        password = code(password);
        User login = userMapper.login(username, password);

        return login;
    }

    /**
     * 用户注册
     *
     * @param user
     */
    @Override
    public void register(User user) {
        String password = user.getPassword();
        password = code(password);
        user.setPassword(password);
//        user.setPermissions("1");
        user.setStatus("2");
        userMapper.register(user);
    }

    /**
     * 用户登录时改变状态
     */
    @Override
    public void updateStatusLogin(String username) {
        userMapper.updateStatusLogin(username);
    }

    /**
     * 用户退出时改变状态
     */
    @Override
    public void updateStatusLogout(String username) {
        userMapper.updateStatusLogout(username);
    }

    /**
     * 根据用户名查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public User getUserInfo(String username) {
        User userInfo = userMapper.getUserInfo(username);
        String height = userInfo.getHeight();
        String weight = userInfo.getWeight();
        String years = userInfo.getYears();
        String substring = height.substring(0, 3);
        int heights = Integer.parseInt(substring);
        int weights = Integer.parseInt(weight);
        int yearss = Integer.parseInt(years);
        String labor = userInfo.getLabor();
        String gender = userInfo.getGender();
        String energy = "";
        double BMR = 0;
        if ( "1".equals(labor)) {
            userInfo.setLabor("乏活动");
            BMR=1.2;
        } else if ("2".equals(labor)) {
            userInfo.setLabor("轻度活动");
            BMR=1.4;
        } else if( "3".equals(labor)) {
            userInfo.setLabor("中度活动");
            BMR=1.6;
        }else if( "4".equals(labor)) {
            userInfo.setLabor("重度活动");
            BMR=1.7;
        }else if( "5".equals(labor)) {
            userInfo.setLabor("非常重度活动");
            BMR=1.9;
        }
        if("1".equals(gender)){
            energy=((int)(88 + (13* weights) + (5 *  heights) - (6 * yearss)) * BMR) +"";
            energy=energy.substring(0,4);
            userInfo.setEnergy(energy);
        }else {
            energy=((int)(448 + (9 * weights) + (3 *  heights) - (4 * yearss)) * BMR) +"";
            energy=energy.substring(0,4);
            userInfo.setEnergy(energy);
        }
        if ("1".equals(gender)) {
            userInfo.setGender("男");
        } else {
            userInfo.setGender("女");
        }
        return userInfo;
    }

    @Override
    public void updateUser(String username, String height, String weight, Integer userId, String labor,String years) {
        userMapper.updateUser(username, height, weight, userId, labor,years);
    }

    @Override
    public List<User> findUserPage() {
        List<User> userPage = userMapper.findUserPage();
        List<RelUserRole> list = relUserRoleService.list();
        for (User user : userPage) {
            Optional<RelUserRole> first = list.stream().filter(item -> item.getUserId() == user.getId()).filter(Objects::nonNull).findFirst();
            if(first.isPresent()) {
                user.setRole(first.get().getRoleId().toString());
                Role byId = roleService.getById(user.getRole());
                user.setRole(byId.getRoleName());
            }else {
                user.setRole("");
            }

            if ("0".equals(user.getGender())) {
                user.setGender("女");
            } else if ("1".equals(user.getGender())) {
                user.setGender("男");
            }
            if ("1".equals(user.getStatus())) {
                user.setStatus("在线");
            } else if ("2".equals(user.getStatus())) {
                user.setStatus("不在线");
            }
            if ( "1".equals(user.getLabor())) {
                user.setLabor("乏活动");
            } else if ("2".equals(user.getLabor())) {
                user.setLabor("轻度活动");
            } else if( "3".equals(user.getLabor())) {
                user.setLabor("中度活动");
            }else if( "4".equals(user.getLabor())) {
                user.setLabor("重度活动");
            }else if( "5".equals(user.getLabor())) {
                user.setLabor("非常重度活动");
            }
        }
        return userPage;
    }

    @Override
    public int findTotal() {
        int total = userMapper.findTotal();
        return total;
    }

    @Override
    public User findById(Integer id) {
        User byId = baseMapper.selectById(id);
        List<RelUserRole> list = relUserRoleService.list();
        for(RelUserRole roleUser : list) {
            if(roleUser.getUserId() == byId.getId()) {
                byId.setRole(roleUser.getRoleId().toString());
                break;
            }
        }
        List<Role> roles = roleService.list();
        for(Role role : roles) {
            if(role.getId() == Integer.parseInt(byId.getRole())) {
                byId.setRole(role.getRoleName());
                break;
            }
        }
        byId.setRoles(roles);
        return byId;
    }

    @Override
    public void userPut(User user) {
        String password = user.getPassword();
        String code = code(password);
        user.setPassword(code);
        userMapper.userPut(user);
    }

    @Override
    public void deleteUser(int id) {
        baseMapper.deleteById(id);
        QueryWrapper<RelUserRole> relUserRoleQueryWrapper = new QueryWrapper<>();
        relUserRoleQueryWrapper.eq("user_id", id);
        relUserRoleService.remove(relUserRoleQueryWrapper);
    }

    @Override
    public void updateUserSmall(User user) {
        String password = user.getPassword();
        String code = code(password);
        user.setPassword(code);
        userMapper.updateUserSmall(user);
    }


    public static String code(String str){
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte[]byteDigest = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < byteDigest.length; offset++) {
                i = byteDigest[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            //32位加密
            return buf.toString();
            // 16位的加密
            //return buf.toString().substring(8, 24);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }

    }
}

